package com.bill99.schedule;

import com.bill99.model.EmailProperties;
import com.bill99.model.TableauProperties;
import com.bill99.service.TableauService;
import com.bill99.service.impl.TableauServiceImpl;
import com.bill99.util.DateUtil;
import com.bill99.util.DtsEmailUtils;
import com.bill99.util.EmailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * 新数据平台运行任务dashboard
 * 
 */
@Component
public class SendDTSRunningTaskDashboardTask {

	@Autowired
	private EmailUtil emailUtil;

	@Resource(name = "tableauServiceImpl")
	public TableauService service;

	@Autowired
	private TableauProperties tableau;

	@Autowired
	private EmailProperties emailProperties;

	private static final Logger LOGGER = LoggerFactory
			.getLogger(SendDTSRunningTaskDashboardTask.class);

	/***
	 * describe: execute creat_time: 2018/7/24 15:48 param: [] return: void
	 */
	@Scheduled(cron = "0 00 04 * * ?")
	public void executeInternal() {

		LOGGER.info("SendDTSRunningTaskDashboardTask execute start.");
		try {
			String emailAddresses = "li.fang@99bill.com,zhenyu.peng@99bill.com,wei.zhang2@99bill.com,shujing.huang@99bill.com,RD_DTS@99bill.com,POA_PLE_SYS@99bill.com";
			String subject = "【日报】数据平台运行状态dashboard";

			TableauProperties myTableau = initTableauProperties(emailAddresses,
					subject);
			LOGGER.info("SendDTSRunningTaskDashboardTask tableau={}", myTableau);

			sendEmail(myTableau, tableau);

		} catch (Exception e) {

			LOGGER.error(
					"SendDTSRunningTaskDashboardTask | execute | Exception", e);
			throw new RuntimeException();
		} finally {
			LOGGER.info("SendDTSRunningTaskDashboardTask execute end.");
		}
	}

	@Scheduled(cron = "0 40 16 ? * FRI")
	public void sendWeeklyDashboard() {

		LOGGER.info("SendWeeklyDashboard execute start.");
		try {
			String emailAddresses = "li.fang@99bill.com,wei.zhang2@99bill.com,RD_DTS@99bill.com,POA_PLE_SYS@99bill.com,shujing.huang@99bill.com";
			String subject = "【周报】数据平台运行状态dashboard";

			TableauProperties myTableau = initTableauProperties(emailAddresses,
					subject);

			LOGGER.info("SendWeeklyDashboard tableau={}", tableau);

			sendEmail(myTableau, tableau);

		} catch (Exception e) {

			LOGGER.error("SendWeeklyDashboard | execute | Exception", e);
			throw new RuntimeException();
		} finally {
			LOGGER.info("SendWeeklyDashboard execute end.");
		}
	}
/*
	@Scheduled(cron = "0 30 * * * ?")
	public void sendMyselfTest() {

		LOGGER.info("SendDTSRunningTaskDashboardTask execute start.");
		try {
			String emailAddresses = "shujing.huang@99bill.com";
			String subject = "【测试】数据平台运行状态dashboard";

			TableauProperties myTableau = initTableauProperties(emailAddresses,
					subject);
			LOGGER.info("SendDTSRunningTaskDashboardTask tableau={}", myTableau);

			sendEmail(myTableau, tableau);

		} catch (Exception e) {

			LOGGER.error(
					"SendDTSRunningTaskDashboardTask | execute | Exception", e);
			throw new RuntimeException();
		} finally {
			LOGGER.info("SendDTSRunningTaskDashboardTask execute end.");
		}
	}
	*/
	private void sendEmail(TableauProperties myTableau,
			TableauProperties tableau) throws Exception {
		List<String> fileNames = service.generatePicByWorkbook(myTableau,
				tableau);

		Map<String, String> params = new HashMap();
		params.put("subject", myTableau.getSubject());
		params.put("whichView", myTableau.getViewName1());
		params.put("emailAddresses", myTableau.getEmailAddresses());// 收件人列表，多个用','隔开
		params.put("templateId", myTableau.getTemplateId());// 模板ID

		String names = "";
		for (int i = 0; i < fileNames.size(); i++) {
			names += myTableau.getAttachmentsPrefix() + fileNames.get(i) + ",";
			params.put("filename" + (i + 1), fileNames.get(i));
			params.put("htmlParam" + (i + 1), myTableau.getAttachmentsPrefix() + fileNames.get(i));
		}
		
		params.put("attachments", names);
		System.out.println(params.get("attachments"));
		params.put("sendEmailUrl", emailProperties.getInterfaceUrl());
		params.put("attchCount", String.valueOf(fileNames.size()));
		String htmlTemplate = initHtmlTemplate();
		params.put("htmlTemplate", htmlTemplate);
		params.put("htmlParamCount", String.valueOf(fileNames.size()));
		
		LOGGER.info("SendDTSRunningTaskDashboardTask params={}", params);
		DtsEmailUtils.sendEmail(params);
//        EmailUtil emailUtil=new EmailUtil();
//        emailUtil.send(params);
		}

	private TableauProperties initTableauProperties(String emailAddresses,
			String subject) {
		TableauProperties myTableau = new TableauProperties();
		String viewName1 = "数据平台运行状态";

		String templateId = "197181097";
		String filePath = "SJPT"
				+ DateUtil.formatDateTime("yyyyMMdd",
						new Date((new Date().getTime() - 86400000L))) + "/";

		myTableau.setSubject(subject);
		myTableau.setViewName1(viewName1);
		myTableau.setEmailAddresses(emailAddresses);
		myTableau.setTemplateId(templateId);
		myTableau.setAttachmentsPrefix(tableau.getAttachmentsPrefix()
				+ filePath);
		LOGGER.info("SendDTSRunningTaskDashboardTask attachmentsPrefix={}",
				myTableau.getAttachmentsPrefix());

		myTableau.setUploadPath(tableau.getUploadPath() + filePath);
		crtFolder(myTableau.getUploadPath());
		LOGGER.info("SendDTSRunningTaskDashboardTask uploadPath={}",
				myTableau.getUploadPath());
		return myTableau;
	}

	public static void main(String[] args) throws Exception {

		TableauProperties tableau = new TableauProperties();
		String subject = "【日报】数据平台运行状态dashboard";
		String viewName1 = "数据平台运行状态";
		// String emailAddresses =
		// "li.fang@99bill.com,zhenyu.peng@99bill.com,wei.zhang2@99bill.com,shujing.huang@99bill.com,RD_DTS@99bill.com";
		// String emailAddresses = "RD_DTS@99bill.com,shujing.huang@99bill.com";

		String emailAddresses = "shujing.huang@99bill.com";
		String templateId = "197181098";
		String filePaht = "SJPT"
				+ DateUtil.formatDateTime("yyyyMMdd",
						new Date((new Date().getTime() - 86400000L))) + "/";
		String attachmentsPrefix = "http://192.168.15.164:8888/tableauViewPic/"
				+ filePaht;
		String name = "99billadmin";
		String password = "wanda.2018";
		String contentUrl = "DM_TEST1";
		String url = "https://tableau.99bill.net/api/2.7/auth/signin";

		String uploadPath = "D:\\test1/" + filePaht;
		// String uploadPath = "http://192.168.15.164:8888/tableauViewPic/" +
		// filePaht;
		crtFolder(uploadPath);

		tableau.setSubject(subject);
		tableau.setViewName1(viewName1);
		tableau.setEmailAddresses(emailAddresses);
		tableau.setTemplateId(templateId);
		tableau.setAttachmentsPrefix(attachmentsPrefix);

		tableau.setName(name);
		tableau.setPassword(password);
		tableau.setContentUrl(contentUrl);
		tableau.setUrl(url);
		tableau.setUploadPath(uploadPath);

		EmailProperties emailProperties = new EmailProperties();
		String interfaceUrl = "http://192.168.127.38:8084/email-prepare/sendEmail.do";

		TableauService service = new TableauServiceImpl();
		List<String> fileNames = service
				.generatePicByWorkbook(tableau, tableau);

		emailProperties.setInterfaceUrl(interfaceUrl);

		Map<String, String> params = new HashMap();
		params.put("subject", tableau.getSubject());
		params.put("whichView", tableau.getViewName1());
		params.put("emailAddresses", tableau.getEmailAddresses());// 收件人列表，多个用','隔开
		params.put("templateId", tableau.getTemplateId());// 模板ID

		String names = "";
		for (int i = 0; i < fileNames.size(); i++) {
			names += attachmentsPrefix + fileNames.get(i) + ",";
			params.put("filename" + (i + 1), fileNames.get(i));
			params.put("htmlParam" + (i + 1), attachmentsPrefix + fileNames.get(i));
		}
		params.put("attachments", names);
		System.out.println(params.get("attachments"));
		params.put("sendEmailUrl", emailProperties.getInterfaceUrl());
		params.put("attchCount", String.valueOf(fileNames.size()));
//		String htmlTemplate = "";
		SendDTSRunningTaskDashboardTask task = new SendDTSRunningTaskDashboardTask();
		String htmlTemplate = task.initHtmlTemplate();
		params.put("htmlTemplate", htmlTemplate);
		params.put("htmlParamCount", String.valueOf(fileNames.size()));

		DtsEmailUtils.sendEmail(params);
		
//		 EmailUtil emailUtil=new EmailUtil();
//       emailUtil.send(params);
	}

	public String initHtmlTemplate(){
    	String htmlTemplate = 
    			"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
    	                "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
    	                "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" +
    	                "</head>\n" +
    	                "<body>\n" +
    	                "<br>\n " +
    	     " Hi All：</span>\n " +
    	      "<br>\n " +
    	      "  这里是您的数据平台运行状态订阅(详情见附件),数据由DTS提供计算服务,如有疑问请联系li.fang@99bill.com</span>\n " +
    	    "  <br>  \n " +
    	   "  新数据平台运行状态<br>\n " +
    	"<p><img src=${htmlParam1}></p><br>\n " +
    	"本周期任务总览<br>\n " +
    	"<p><img src=${htmlParam2}></p><br>\n " +
    	"任务数据量过大<br>\n " +
    	"<p><img src=${htmlParam3}></p><br>\n " +
    	"任务执行时间过长<br>\n " +
    	"<p><img src=${htmlParam4}></p><br>\n " +
    	"任务占用CPU过大<br>\n " +
    	"<p><img src=${htmlParam5}></p><br>\n " +
    	"任务占用内存过大<br>\n " +
    	"<p><img src=${htmlParam6}></p><br>\n " +
    	"失败任务<br>\n " +
    	"<p><img src=${htmlParam7}></p><br>\n " +
    	"多次执行任务失败<br>\n " +
    	"<p><img src=${htmlParam8}></p><br>\n " +
    	"重复执行任务过于频繁<br>\n " +
    	"<p><img src=${htmlParam9}></p><br>\n " +
    	"  <p>\n " +

    	"<a href=\"http://tableau.99bill.net/#/site/DM_TEST1/user/local/DTS_USER4/subscriptions\">管理我的订阅</a></p>\n " +

    	" 此为系统自动邮件，请勿回复。" +
    	 "     <br>" +
    	   " 多谢!" +
    	                "</body></html>";
    	return htmlTemplate;
    }

	public static void crtFolder(String filePaht) {
		File file = new File(filePaht);
		if (!file.exists()) {
			file.mkdirs();
		}

	}

}
